package com.skyworthclub.competition.controller;

import com.skyworthclub.competition.beans.Match;
import com.skyworthclub.competition.beans.dto.DateRangeDto;
import com.skyworthclub.competition.service.MatchElasticsearchService;
import com.skyworthclub.competition.service.MatchService;
import com.skyworthclub.competition.utils.web.DataValidateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.chrono.IsoChronology;
import java.util.HashMap;
import java.util.Map;

/**
 * @author li
 * @version 1.0
 * @since 18-10-19 下午1:28
 * 搜索控制器
 **/
@Controller
@RequestMapping("/api/search")
public class SearchController {

    private final MatchElasticsearchService elasticsearchService;
    private final MatchService matchService;

    @Autowired
    public SearchController(MatchElasticsearchService elasticsearchService, MatchService matchService) {
        this.elasticsearchService = elasticsearchService;
        this.matchService = matchService;
    }

    /**
     * 综合搜索，默认按照如下五个字段搜索:
     * "matchName", "matchSummary", "matchDetail", "matchOrganizer", "matchContestants"
     */
    @GetMapping("")
    public ResponseEntity<Map<String, Object>> search(@RequestParam(value = "q") String keyword,
                                                      @RequestParam(value = "page", required = false) Integer page,
                                                      @RequestParam(value = "getall", required = false) Integer getall) {
        Map<String, Object> map = new HashMap<>(4);
        if (getall != null && getall == 1) {
            Iterable<Match> matches = elasticsearchService.multiMatchQuery(keyword, null);
            map.put("matches", matches);
        } else {
            if (page == null || page < 1) {
                page = 1;
            }
            Page<Match> matchPage = elasticsearchService.multiMatchQuery(keyword, page, null);
            //转换Page对象使接口统一
            com.baomidou.mybatisplus.plugins.Page<Match> matches = new com.baomidou.mybatisplus.plugins.Page<>();
            matches.setRecords(matchPage.getContent());
            matches.setCurrent(matchPage.getNumber() + 1);
            matches.setSize(matchPage.getSize());
            matches.setTotal(matchPage.getTotalElements());
            map.put("matches", matches);
        }

        return new ResponseEntity<>(map, HttpStatus.OK);
    }

    /**
     * 按月份查询
     */
    @GetMapping("/{year}/{month}")
    public ResponseEntity<Map<String, Object>> searchByMonth(@PathVariable Integer year,
                                                             @PathVariable Integer month,
                                                             @RequestParam(value = "page", required = false) Integer page) {

        if (page == null) {
            page = 1;
        }
        //构造日期
        LocalDate startDate = LocalDate.of(year, month, 1);
        int length = startDate.getMonth().length(IsoChronology.INSTANCE.isLeapYear((long) year));
        LocalDate endDate = LocalDate.of(year, month, length);
        //查询

        com.baomidou.mybatisplus.plugins.Page<Match> matchPage = matchService.searchByRange(startDate, endDate, page);

        Map<String, Object> map = new HashMap<>(4);
        map.put("matches", matchPage);
        return new ResponseEntity<>(map, HttpStatus.OK);
    }

    /**
     * 自定义日期范围查询
     */
    @PostMapping("/range/{pageNum}")
    public ResponseEntity<Map<String, Object>> searchByRange(@RequestBody DateRangeDto dateRangeDto,
                                                             Errors errors,
                                                             @PathVariable Integer pageNum) {
        if (pageNum <= 0) {
            pageNum = 1;
        }
        ResponseEntity<Map<String, Object>> responseEntity = DataValidateUtil.validate(errors);
        if (responseEntity != null) {
            return responseEntity;
        }
        com.baomidou.mybatisplus.plugins.Page<Match> matches = matchService.searchByRange(dateRangeDto.getBegin(), dateRangeDto.getEnd(), pageNum);
        Map<String, Object> map = new HashMap<>(4);
        map.put("matches", matches);
        return new ResponseEntity<>(map, HttpStatus.OK);
    }

}
